package org.example.Utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.example.Entity.User;
import org.example.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class HttpUtil {

    @Autowired
    private UserService userService;

    /**
     * HTTP接口-GET方式，请求参数形式为params形式
     *
     * @param url
     * @param param
     * @return String
     */
    public static String sendGet(String url, String param) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .writeTimeout(180, TimeUnit.SECONDS)
                .build();

        String dataUrl = url + param;
        Request request = new Request.Builder()
                .url(dataUrl)
                .get()
                .build();
        Response response;
        String result = null;
        try {
            response = client.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public Integer getUserId(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userService.getOne(wrapper);
        return user.getId();
    }
}
